/*
 *   Copyright (C) 2010  Jens Kieselbach
 * 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 * 
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 * 
 *   You may obtain a copy of the License at http://www.gnu.org/licenses/gpl.html
 */

package de.kieselbach.swing

import java.awt.event.*
import javax.swing.*

import java.awt.Dimension
import java.awt.Graphics
import java.awt.Image
import javax.swing.Timer

class ProcessWorkingIcon extends JComponent {

    static int DELAY = 50

    Timer timer
    Image image
    int rows
    int columns
    int tileWidth
    int tileHeight
    int currentRow
    int currentColumn
    boolean running = false

    ProcessWorkingIcon(ImageIcon img, int r, int c) {

        this(img.image, r, c)
    }

	ProcessWorkingIcon(Image img, int r, int c) {

        image = img
        rows = r
        columns = c

        tileWidth = image.width / columns
        tileHeight= image.height / rows

        opaque = false

        timer = new Timer(DELAY, {

            currentColumn++
            if(currentColumn >= columns) {
                currentColumn = 0

                currentRow++
                if(currentRow >= rows) {
                    currentRow = 0
                    if(currentColumn == 0) {
                        currentColumn++
                    }
                }
            }

            repaint()
        } as ActionListener)
    }

    synchronized void start() {

        if (!running) {
            running = true;
            currentRow = 0
            currentColumn = 1
            timer.start();
        }
    }

    synchronized void stop() {

        if (running) {
            running = false;
            currentRow = 0
            currentColumn = 0
            timer.stop();
        }
    }

    protected void paintComponent(Graphics g) {

        super.paintComponent(g)

        int x = (width - tileWidth) / 2
        int y = (height - tileHeight) / 2

        int r = 0
        int c = 0

        if(running) {
            r = currentRow
            c = currentColumn
        }

        int sx = c * tileWidth
        int sy = r * tileHeight

        g.drawImage(image, x, y, x + tileWidth, y + tileHeight, sx, sy, sx + tileWidth, sy + tileHeight, null)
    }
}

